﻿using System;
using System.Drawing;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace hello_accinv_New_
{
    public partial class MainForm : Form
    {
        private TimeSpan loginTime;

        private ToolStripMenuItem selectedMenu;

        public MainForm()
        {
            InitializeComponent();

            SetUsernameAndPermission();
        }

        public void SetUsernameAndPermission()
        {
            usernameToolStripMenuItem.Text = GlobalClass.fullName;
            toolStripStatusLogin.Text = "Logged in as " + GlobalClass.fullName + " [00:00:00]";
            loginTime = DateTime.Now.TimeOfDay;
            timerLoginDuration.Start();
        }

        private void LoadForm(Form form, object control)
        {
            if (selectedMenu != (ToolStripMenuItem)control)
            {
                Cursor = Cursors.WaitCursor;

                // If there is currently opened form
                if (MdiChildren.Length > 0)
                {
                    CloseCurrentMdiChild();
                }

                // If there is no opened form (latest form is closed succesfully)
                if (MdiChildren.Length == 0)
                {
                    // Open form
                    form.MdiParent = this;
                    form.Show();
                    form.WindowState = FormWindowState.Maximized;
        
                    // Get selected menu and set colors
                    selectedMenu = ((ToolStripMenuItem)control);
                    //selectedMenu.BackColor = Color.SkyBlue;
                    //selectedMenu.ForeColor = Color.White;

                    closeToolStripMenuItem.Visible = true;
                }

                Cursor = Cursors.Default;
            }
        }

        private void CloseCurrentMdiChild()
        {
            // Try to close Child form
            MdiChildren[0].Close();

            // If form is closed
            if (MdiChildren.Length == 0)
            {
                // Reset menu colors
                //selectedMenu.BackColor = System.Windows.Forms.Control.DefaultBackColor;
                //selectedMenu.ForeColor = System.Windows.Forms.Control.DefaultForeColor;
                selectedMenu = null;

                closeToolStripMenuItem.Visible = false;

                // Force running Garbage Collector
                GC.Collect();
            }
        }

        private void UpdateLoginDuration()
        {
            toolStripStatusLogin.Text = "Logged in as " + GlobalClass.fullName + 
                " [" + DateTime.Now.Subtract(loginTime).ToLongTimeString() + "]";
        }

        private void saleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadForm(new SaleForm(), sender);
        }

        private void inventoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadForm(new InventoryForm(), sender);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainForm_FormClosing(sender, new FormClosingEventArgs(CloseReason.None, false));
        }

        private void stockToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadForm(new StockReportForm(), sender);
        }

        private void saleToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            LoadForm(new SaleReportForm(), sender);
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CanLogoutOrExit())
            {
                if (MessageBox.Show("Logout?", "Logout", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    == System.Windows.Forms.DialogResult.Yes)
                {
                    DialogResult = System.Windows.Forms.DialogResult.Retry;
                    Dispose();
                }
            }
        }

        private void timerLoginDuration_Tick(object sender, EventArgs e)
        {
            UpdateLoginDuration();
        }

        private void usageLogsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadForm(new LogForm(), sender);
        }

        private void usersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadForm(new UserSettingForm(), sender);
        }

        private void repairDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MdiChildren.Length > 0)
            {
                MessageBox.Show("Close current window before repairing database.", "Repair database", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                if (MessageBox.Show("Repair database?", "Repair database", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
                    == System.Windows.Forms.DialogResult.Yes)
                {
                    Cursor = Cursors.WaitCursor;

                    MySqlConnection conn = new MySqlConnection("Server=localhost;" +
                                                                "Uid=root;" +
                                                                "Pwd=;" +
                                                                "CharSet=utf8;" +
                                                                "Allow Zero Datetime=True;");
                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = conn;
                    conn.Open();
                    
                    try
                    {
                        cmd.CommandText = "DROP DATABASE accinv";
                        cmd.ExecuteNonQuery();
                    }
                    catch (MySqlException ex) { Console.WriteLine(ex.Message); }
                    
                    cmd.CommandText = "SET NAMES UTF8";
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "CREATE DATABASE accinv CHARACTER SET utf8 COLLATE utf8_general_ci";
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "USE accinv";
                    cmd.ExecuteNonQuery();

                    string[] tableList = hello_accinv_New_.Properties.Resources.Database.Split(';');
                    foreach (string table in tableList)
                    {
                        if (!table.Equals(""))
                        {
                            cmd.CommandText = table;
                            cmd.ExecuteNonQuery();
                        }
                    }

                    conn.Close();
                    conn = null; cmd = null;

                    Cursor = Cursors.Default;
                    MessageBox.Show("Repairing is finished.");
                }
            }
        }

        private bool CanLogoutOrExit()
        {
            // Try to close current form
            if (MdiChildren.Length > 0)
            {
                CloseCurrentMdiChild();
            }

            // If form is closed
            if (MdiChildren.Length == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult != System.Windows.Forms.DialogResult.Retry)
            {
                if (CanLogoutOrExit())
                {
                    if (MessageBox.Show("Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                        == System.Windows.Forms.DialogResult.Yes)
                    {
                        DialogResult = System.Windows.Forms.DialogResult.Abort;
                        Dispose();
                    }
                    else
                    {
                        e.Cancel = true;
                    }
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CloseCurrentMdiChild();
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            Refresh();
        }
    }
}
